<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="4" :sm="24">
            <a-form-item label="定义名">
              <a-input v-model="queryParam.name" placeholder="请输入搜索关键字" />
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item label="显示名">
              <a-input v-model="queryParam.display_name" placeholder="请输入搜索关键字" />
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 8px" @click="queryParam = {};$refs.table.refresh(true);">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="table-operator">
      <a-button
        v-if="$auth('admin.sys-role.save')"
        type="primary"
        icon="plus"
        @click="$refs.createModal.add()">新建角色</a-button>
      <a-button v-if="$auth('admin.sys-role.batchdel')" type="danger" style="margin-left: 8px" @click="handleBatchDel" icon="delete">
        批量删除
      </a-button>
    </div>
    <s-table
      ref="table"
      size="default"
      rowKey="role_id"
      :defaultExpandAllRows="true"
      :columns="columns"
      :data="loadData"
      :alert="options.alert"
      :rowSelection="options.rowSelection"
      showPagination="auto"
    >
      <div
        slot="action"
        slot-scope="text, record">
        <template>
          <a-button
            size="small"
            icon="plus"
            type="primary"
            v-if="$auth('admin.sys-role.save')"
            @click="$refs.createModal.addChild(record)">添加子角色</a-button>
          <a-divider type="vertical" />
          <a-button
            size="small"
            icon="edit"
            type="primary"
            v-if="$auth('admin.sys-role.save')"
            @click="$refs.createModal.edit(record)">编辑</a-button>
          <a-divider type="vertical" />
          <a-button
            size="small"
            icon="delete"
            type="danger"
            v-if="$auth('admin.sys-role.destroy')"
            @click="handleDel(record)">删除</a-button>
        </template>
      </div>
    </s-table>
    <create-form
      ref="createModal"
      :treePermData="permList"
      @ok="handleRefresh" />
  </a-card>
</template>

<script>
import { STable } from '@/components'
import CreateForm from './modules/SysRoleCreateForm'
import { getList, delData } from '@/api/system/sysrole'
const permFormatter = (list) => {
  if (list === null) return []
  const re = list.map(
    (item) => {
      const result = {
        children: [],
        value: item.perm_id,
        title: item.display_name,
        parent_id: item.parent_id
      }
      if (item.children != null) {
        result.children = permFormatter(item.children)
      }
      return result
    }
  )
  return re
}

export default {
  name: 'SysRole',
  components: {
    STable,
    CreateForm
  },
  data () {
    return {
      tableData: [],
      permList: [],
      // 查询参数
      queryParam: {},
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: 'role_id'
        },
        {
          title: '角色定义名',
          dataIndex: 'name'
        },
        {
          title: '角色显示名',
          dataIndex: 'display_name'
        },
        {
          title: '描述',
          dataIndex: 'description'
        },
        {
          title: '排序',
          dataIndex: 'order_num'
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return getList(Object.assign(parameter, this.queryParam))
          .then(res => {
            this.permList = permFormatter(res.data.permList)
            return {
              pageNo: res?.data?.page || 1,
              totalCount: res?.data?.total || 0,
              data: res?.data?.roleList || []
              }
          })
      },
      selectedRowKeys: [],
      selectedRows: [],
      // custom table alert & rowSelection
      options: {
        alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      }
    }
  },
  filters: {},
  mounted () {
  },
  methods: {
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleEdit (record) {
      console.log(record)
      this.$refs.createModal.edit(record)
    },
    handleBatchDel () {
      this.$confirm({
        title: '你确定要删除所有选中角色？',
        content: '此操作将永久删除角色, 是否继续?',
        onOk: () => {
          return delData(this.selectedRowKeys).then(res => {
            if (res.code === 0) {
              this.handleRefresh()
              this.selectedRowKeys = []
              this.$message.success(
                '删除角色成功'
              )
            }
          }).catch((error) => console.error(error))
        },
        onCancel () {
        }
      })
    },
    handleDel (record) {
      this.$confirm({
        title: '你确定要删除该角色？',
        content: '此操作将永久删除该角色, 是否继续?',
        onOk: () => {
          return delData([record.role_id]).then(res => {
            if (res.code === 0) {
              this.handleRefresh()
              this.$message.success(
                '删除角色成功'
              )
            }
          }).catch((error) => console.error(error))
        },
        onCancel () {
        }
      })
    },
    handleRefresh () {
      this.$refs.table.refresh()
    }
  }
}
</script>
